package com.slimbloody;

import protobuf.SSLConfigClass;

import java.io.*;
import java.util.stream.Collectors;
import com.google.protobuf.TextFormat;

public class PbTest {
  public static String readFile(String fileName) {
    try (InputStream inputStream = PbTest.class.getClassLoader().getResourceAsStream(fileName)) {
      if (inputStream == null) {
        System.err.println("文件未找到：" + fileName);
        return null;
      }

      try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
        String lines = reader.lines().collect(Collectors.joining("\\n"));
        // System.out.printf("fileName: %s, content: %s\n", fileName, lines);
        System.out.println(fileName);
        System.out.println(lines);
        return lines;
      } catch (Exception e) {
        throw new RuntimeException("读取文件时出错: " + fileName, e);
      }

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) {
    SSLConfigClass.SSLConfig.Builder builder = SSLConfigClass.SSLConfig.newBuilder();
    builder.setServerKey(readFile("grpc.key"));
    builder.setServerCert(readFile("grpc.crt"));
    builder.setClientVerify(false);
    SSLConfigClass.SSLConfig sslConfig = builder.build();

    // Save to pbtxt (ASCII format)
    try (FileWriter writer = new FileWriter("ssl_config.pbtxt")) {
      String printStr = TextFormat.printer().escapingNonAscii(false).printToString(sslConfig);
      writer.write(printStr);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // // Step 4: Write to binary `.pb` file
    // try (FileOutputStream fos = new FileOutputStream("ssl_config.pb")) {
    //   sslConfig.writeTo(fos);
    //   System.out.println("ssl_config.pb");
    // } catch (IOException e) {
    //   e.printStackTrace();
    // }
  }
}
